import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

from core.database import init_database
from apps.users.views import router as auth_router
from apps.meetings.views import router as meetings_router

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
    handlers=[
        logging.FileHandler('app.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 应用生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理，包含启动初始化和关闭清理"""
    # 启动阶段
    try:
        logger.info("正在初始化数据库...")
        init_database()
        logger.info("数据库初始化完成")
        logger.info("后端服务启动完成")
    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        raise
    
    # 运行阶段
    yield
    
    # 关闭阶段
    logger.info("应用正在关闭...")
    logger.info("清理资源完成")

# 创建FastAPI应用实例
app = FastAPI(
    title="本地会议助手API",
    description="提供用户认证、会议录音转录、翻译和AI分析功能的后端服务",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS中间件，允许前端跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],  # 更安全的配置
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth_router)
app.include_router(meetings_router, prefix="/api/v1")

# 全局异常处理
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    """HTTP异常处理器"""
    logger.warning(f"HTTP异常: {exc.status_code} - {exc.detail}")
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "message": exc.detail,
            "status_code": exc.status_code
        }
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    """请求验证异常处理器"""
    logger.warning(f"请求验证失败: {exc.errors()}")
    return JSONResponse(
        status_code=422,
        content={
            "success": False,
            "message": "请求参数验证失败",
            "errors": exc.errors()
        }
    )

@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
    """通用异常处理器"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "message": "服务器内部错误，请稍后重试"
        }
    )

# 健康检查接口
@app.get("/health")
async def health_check():
    """健康检查接口，用于监控服务状态"""
    return {
        "status": "healthy",
        "message": "服务运行正常"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app", 
        host="0.0.0.0", 
        port=8000, 
        reload=True,
        log_level="info"
    )